package com.ykt.service;

import com.ykt.common.constant.ParamNames;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.model.Shop;
import com.ykt.model.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author long.hua
 * @version 1.0.0
 * @since 2016-01-17 14:10
 */
public class ShopService {

    private User userDao = User.dao;
    private Shop shopDao = Shop.dao;


    /**
     * 查询商铺列表
     * @param param 市场id、 分类id、商铺名称和分页参数
     * @return
     */
    public PageData<Shop> paginate(PageParam<Map<String, Object>> param){
        PageData<Shop> pd = shopDao.paginate(param);
        if(pd == null || pd.getPageData() == null || pd.getPageData().isEmpty()){
            return pd;
        }

        // 添加商户头像
        List<Integer> ids = new ArrayList<>();
        for (Shop entity : pd.getPageData()) {

            Integer merchantId = entity.getInt(Shop.merchant_id);
            if(merchantId != null && !ids.contains(merchantId)){
                ids.add(merchantId);
            }
        }

        List<User> users = userDao.findByIds(ids);
        if(users == null || users.isEmpty()){
            return pd;
        }

        Map<Integer, User> userMap = new HashMap<>();
        for (User entity : users) {
            userMap.put(entity.getInt(User.id), entity);
        }

        for (Shop entity : pd.getPageData()) {
            Integer merchantId = entity.getInt(Shop.merchant_id);
            if(merchantId != null){
                User user = userMap.get(merchantId);
                if(user == null){
                    continue;
                }

                entity.put(ParamNames.merchantPhone, user.get(User.phone));
                entity.put(ParamNames.merchantName, user.get(User.name));
                entity.put(ParamNames.merchantHead, user.get(User.head));
            }
        }

        return pd; // 因为引用无需再设置到pd变量中
    }


    public Shop findById(int shopId){
        return shopDao.findById(shopId);
    }

}
